package com.qf.openapi.web.master.filter;

import com.qf.openapi.web.master.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/logout")
@Slf4j
public class LogoutFile implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("Logout 初始化成功");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest)request;
        final HttpServletResponse ses = (HttpServletResponse)response;
        log.debug("删除session中的user对象");
        final HttpSession session = req.getSession();
        session.setAttribute(Constants.USER_SESSION_KEY, null);
        final Cookie cookie = new Cookie(Constants.USER_AUTOLOGIN_TOKEN,null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        ses.addCookie(cookie);
        log.debug("cookie已清理");
        ses.sendRedirect("/login.html");
    }

    @Override
    public void destroy() {
        log.debug("LogoutFilter 注销");
    }
}
